package awk.thread;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yujianlong
 * @create 2021-03-24 10:00
 **/

public class MyZTAPIContextHolder {
	private static final TransmittableThreadLocal<HashMap<String, String>> contextNew = new TransmittableThreadLocal<>();

//	private static final ThreadLocal<HashMap<String, String>> context = new ThreadLocal<>();
	public static void init() {
		MyZTAPIContextHolder.clear();
		MyZTAPIContextHolder.contextNew.set(new HashMap<>());
	}

	public static void clear() {
		HashMap<String, String> tmp = MyZTAPIContextHolder.contextNew.get();
		if (tmp != null) {
			MyZTAPIContextHolder.contextNew.set(null);
			tmp.clear();
		}
	}

	public static HashMap<String, String> data() {
		HashMap<String, String> tmp = MyZTAPIContextHolder.contextNew.get();
		return (null == tmp) ? new HashMap<>() : tmp;
	}

	public static Object get(String key) {
		if (null == MyZTAPIContextHolder.contextNew.get()) {
			MyZTAPIContextHolder.init();
		}
		return MyZTAPIContextHolder.contextNew.get().get(key);
	}

	public static Object getOrDefault(String key, Object defaultValue) {
		Object rtn = MyZTAPIContextHolder.get(key);
		return rtn == null ? defaultValue : rtn;
	}

	public static void set(Map<String, String> entries) {
		MyZTAPIContextHolder.contextNew.get().putAll(entries);
	}

	public static void set(String key, Object value) {
		MyZTAPIContextHolder.contextNew.get().put(key, String.valueOf(value));
	}
}
